package reptile

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"robot/study/LiveRobot/define"
	"robot/study/LiveRobot/sdk/zlog"
	"strconv"
	"time"
)

type Sweet struct {
	U *define.Message2
}

//翻译
func (sw *Sweet) Work() {
	rand.Seed(time.Now().Unix())
	randNum := strconv.Itoa(rand.Int() % 100)
	str := sw.U.RawMessage[9:]
	md5s := "20211022000979502" + str + randNum + "ncxDi52HxjWDp95ZplsC"
	zlog.Info("翻译内容:", str)
	zlog.Info(md5s)
	sign := md5Get(md5s)
	resp, err2 := http.Get("http://fanyi-api.baidu.com/api/trans/vip/translate?" + "q=" + str + "&from=auto&to=en&appid=20211022000979502&salt=" + randNum + "&sign=" + sign)
	if err2 != nil {
		zlog.Error("请求翻译失败")
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)
	body, _ := ioutil.ReadAll(resp.Body)
	var re define.Result
	fmt.Println(string(body))
	err3 := json.Unmarshal(body, &re)
	if err3 != nil {
		zlog.Error("解析失败")
	}
	if re.Trans_result == nil {
		msg := &define.Msg{
			Msg_type: sw.U.MessageType,
			Number:   int(sw.U.GroupId),
			Msg:      "翻译失败嘤嘤嘤",
		}
		Sendmsg(msg)
		return
	}
	msg := &define.Msg{
		Msg_type: sw.U.MessageType,
		Number:   int(sw.U.GroupId),
		Msg:      re.Trans_result[0].Dst,
	}
	Sendmsg(msg)
	//Detmsg(re.Trans_result[0].Dst)
}

//md5加密
func md5Get(str string) string {
	m5 := md5.New()
	_, err := m5.Write([]byte(str))
	if err != nil {
		panic(err)
	}
	md5String := hex.EncodeToString(m5.Sum(nil))
	return md5String
}
